<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 员工管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" class="handle-del mr10" @click="addEmplyee">添加员工</el-button>
            <el-select v-model="querysearch.role" placeholder="全部角色" clearable class="handle-select mr10" @change="changeRole">
                <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="querysearch.status" placeholder="全部状态" clearable class="handle-select mr10" @change="changeStatus">
                <el-option key="1" label="已启用" value="1"></el-option>
                <el-option key="0" label="已停用" value="0"></el-option>
            </el-select>
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-select @change="switchAccount" v-model="querysearch.account" class="handle-select mr10">
                    <el-option key="1" label="用户名" value="用户名"></el-option>
                    <el-option key="2" label="昵称" value="昵称"></el-option>
                </el-select>
                <el-input v-model="querysearch.name" :placeholder="`输入` + querysearch.account" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="头像" width="100">
                    <template slot-scope="scope">
                        <!-- <img v-if="scope.row.avatar" :src="scope.row.avatar" class="avatar" height="50px" width="50px"> -->
                        <img :src="scope.row.avatar" @error="tabErrorPicture(scope.row.id)" alt="" class="avatar" v-if="scope.row.avatar" />
                        <img :src="errorProduct" alt="" class="avatar" v-else />
                    </template>    
                </el-table-column>
                <el-table-column prop="nickname" label="昵称"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="title" label="组别"></el-table-column>
                <el-table-column prop="addpeopleusername" label="添加人"></el-table-column>
                <el-table-column prop="addtime" label="添加时间"></el-table-column>
                <el-table-column prop="status" label="状态">
                     <template slot-scope="scope">
                      <span v-if="scope.row.status">启用</span>
                      <span v-if="!scope.row.status">停用</span>
                     </template>
                </el-table-column>
                <!-- <el-table-column prop="cost" label="免/收费"></el-table-column> -->
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template slot-scope="scope">
                        <div class="operation-wrapper">
                            <span @click="stopUser(scope.row.id,scope.row.status)">
                                  <span v-if="scope.row.status==0">启用</span>
                                  <span v-if="scope.row.status==1">停用</span>
                            </span>
                            <div class="line">|</div>
                            <span @click="handleEdit(scope.$index, scope.row)">编辑</span>
                            <div class="line">|</div>
                            <span @click="handleDelete(scope.$index,scope.row.id)" style="color: red">删除</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.limit"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item>
                     <el-button @click="chooseLecturer" type="primary" size="mini">选择用户</el-button>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="form.nickname" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="form.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户组">
                    <el-select v-model="form.group_id" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
                   </el-select>
                </el-form-item>
                 <el-form-item label="详细信息">
                    <el-input v-model="form.desc" type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

         <el-dialog width="36%" title="选择用户" @close="exit" :visible.sync="addTeacher" append-to-body>
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item>
                    <el-input v-model="query1.keyword" placeholder="输入用户名" class="handle-input mr10"></el-input>
                    <el-button type="primary" icon="el-icon-search" @click="lecturerSearch">搜索</el-button>
                </el-form-item>
                <el-table :data="chooseLecturerTableData" @row-click="chooseRow" class="chooseLecturerTable"
                    ref="multipleTable" header-cell-class-name="table-header">
                    <el-table-column label="用户图片">
                        <template slot-scope="scope">
                            <img :src="scope.row.avatar" alt="" class="info-image" width="50px" height="50px"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="nickname" label="昵称"></el-table-column>
                    <el-table-column prop="username" label="用户名"></el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background layout="total, prev, pager, next" :current-page="query1.page"
                        :page-size="query1.rows" :total="lecturerListTotal" @current-change="lecturerPageChange">
                    </el-pagination>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exit">关 闭</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { staffData,adminListData, getGroupId,editStaffData, stopStaffData,delStaffData,existStaffData,delEmplyee } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            query1: {//添加员工列表
                status: 0,
                page: 1,
                rows: 4,
                keyword: ''
            },
            querysearch: {//查询员工外列表
                role: "",
                status: "",
                account: "",
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            chooseLecturerTableData: [],
            delList: [],
            editVisible: false,
            addTeacher:false,
            pageTotal: 0,
            form: {
                group_id:""
            },
            idx: -1,
            id: -1,
            query:{//查询员工里列表
                page:1,
                limit:4,
                keyword:"",
                group_id:"",
                status:"",
                username:"",
                nickname:""
            },
            options:"",
            lecturerListTotal:0,
            errorProduct: require('@/assets/img/avatar.png'),
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id){    // 表格图文封面默认展示图
            let i = this.tableData.findIndex(v => v.id == id);
			this.tableData[i].avatar = this.errorProduct;
        },        
        getData() { // 获取 easy-mock 的模拟数据
            staffData(this.query).then((res) => {              
                this.tableData = res.data.list;
                this.pageTotal = res.data.total;
            });
            this.getGroupId();
        },
        chooseLecturer() {
            this.addTeacher=true;
            adminListData(this.query1).then((res) => {
                this.chooseLecturerTableData = res.data.list;
                this.lecturerListTotal = res.data.count;
            });
        },
        chooseRow(row) {
            existStaffData({aid:row.id}).then((res)=>{
               if(res.code==1){
                  this.form.aid=row.id;
                  this.form.nickname=row.nickname;
                  this.form.username=row.username;
                  this.addTeacher=false;
               }else{
                  this.$alert('该员工已经存在', '消息提示', {confirmButtonText: '确定'});
               }
            });
            
        },
        switchAccount(value) {
            this.query.account = value;
        },
        // 触发搜索按钮
        handleSearch() {
            if(this.query.account=="用户名"){
                this.query.username=this.querysearch.name;
            }else if(this.query.account=="昵称"){
                this.query.nickname=this.querysearch.name;
            }
            this.getData();
        },
        // 删除操作
        handleDelete(index, id) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                    delStaffData({id}).then((res)=>{
                        if(res.code==1){
                    this.$message.success('删除成功');
                     this.getData();}
                   //this.tableData.splice(index, 1);
                    })
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
             this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
            const length = this.multipleSelection.length;
            let str = '';
            //this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].id + ',';
            }
            str = str.substring(0, str.lastIndexOf(','));
            delEmplyee({str}).then((res)=>{
                if(res.code==1){
                 this.getData();
                 this.$message.success('批量删除成功');
                }else{
                 this.$message.success('批量删除失败');
                }
            });
            this.multipleSelection = [];});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.form = row;
            this.editVisible = true;
            this.form.action='edit';
            //console.log(this.form);
            //this.getGroupId();
       },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            editStaffData(this.form).then((res)=>{
                  if(res.code==1){
                      this.getData();
                      this.$message.success(`保存成功`);
                  }
            });
            this.form=[];
            //this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        addEmplyee(){
            this.form.action='add';
            this.editVisible=true;
            //this.getGroupId();
        },  
        exit(){
            this.addTeacher=false;
        },
        // 讲师搜索
        lecturerSearch() {
            this.chooseLecturer();
        },
        // 讲师分页
        lecturerPageChange(val) {
            this.$set(this.query1, 'page', val);
            this.chooseLecturer();
        },
        //得到管理员分组
        getGroupId(){
            getGroupId().then((res)=>{
                this.options=res.data.list;
            });
        },
        changeRole(value){
            //this.$set(this.query,'group_id',this.querysearch.role);
            this.query.group_id=value;
            this.getData();
        },
        changeStatus(){
            this.query.status=value;
            this.getData();
        },
        stopUser(id, status){
            this.$confirm(`确定${status == 0 ? '启用' : '停用'}吗！`, '提示', {
                type: 'warning'
            }).then(() => {
                stopStaffData({ id: id, status: status == 0 ? 1 : 0 }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('操作成功');
                        this.getData();
                    }else if(res.code==0){
                         this.$message.error('你没有权限修改');
                     }
                });
            });
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-select {
    width: 120px;
}
.avatar{
    height: 50px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.operation-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}
.operation-wrapper span {
    color: #105cfb;
    cursor: pointer;
    position: relative;
    flex-shrink: 0;
}
.operation-wrapper .line {
    margin: 0 3px;
    color: #eeeeee;
    border-radius: 2px;
}
</style>
